package com.mr.util;

import java.io.IOException;
import java.rmi.server.UID;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringUtil extends StringUtils {
	private static BASE64Encoder encoder = new BASE64Encoder();
	private static BASE64Decoder dec = new BASE64Decoder();
	public static String md5(String password) {
		return md5(password, "utf-8");
	}

	public static String md5(String password, String encoding) {
		return encryptPassword(password, encoding, "md5");
	}

	public static String sha(String password, String encoding) {
		return encryptPassword(password, encoding, "sha");
	}

	public static String encryptPassword(String password, String encoding,
			String algorithm) {
		byte[] unencodedPassword = null;
		MessageDigest md = null;
		try {
			unencodedPassword = password.getBytes(encoding);
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			return password;
		}
		md.reset();
		md.update(unencodedPassword);
		byte[] encodedPassword = md.digest();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}
		return buf.toString();
	}

	public static String getUID() {
		String UID = new UID().toString().replace(':', '_').replace('-', '_');
		return UID;
	}

	public static String enabbr(String input, int size) {
		if (StringUtils.isBlank(input))
			return null;
		int bytelength = getByteLength(input);
		if (bytelength < size)
			return input;
		StringBuffer sb = new StringBuffer(input);
		while (bytelength > size) {
			char c = sb.charAt(sb.length() - 1);
			sb.deleteCharAt(sb.length() - 1);
			if (c > 128)
				bytelength -= 2;
			else
				bytelength -= 1;
		}
		return sb.toString();
	}

	public static int getByteLength(String input) {
		if (input == null)
			return 0;
		int length = input.length();
		int byteLength = length;
		for (int i = 0; i < length; i++)
			if (input.charAt(i) > 128)
				byteLength++;
		return byteLength;
	}

	public static String toUnicode(String original) {
		if (original == null)
			return null;
		String result = "";
		for (int i = 0, length = original.length(); i < length; i++) {
			if (original.charAt(i) > 0 && original.charAt(i) < 256)
				result += original.charAt(i);
			else
				result += "\\u"
						+ Integer.toHexString(original.charAt(i)).toUpperCase();
		}
		return result;
	}

	public static String encodeString(String str) {
		return encoder.encodeBuffer(str.getBytes()).trim();
	}
	public static String decodeString(String str) {
		try {
			return new String(dec.decodeBuffer(str));
		} catch (IOException io) {
			throw new RuntimeException(io.getMessage(), io.getCause());
		}
	}
	public static String getNewFileName(MultipartFile file){
		String fileName = DateUtil.format(DateUtil.getCurTimestamp(), "yyyyMMddHHmmss");
		fileName = fileName + "." + getFilenameExtension(file.getOriginalFilename());
		return fileName;
	}
	public static String getFilenameExtension(String path) {
		if (path == null) {
			return null;
		}
		int sepIndex = path.lastIndexOf('.');
		return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);
	}
	public static void main(String[] args) {
		System.out.println(md5("xxxx"));
	}
	public static String getJsonData(HttpServletRequest request, String ...params){
		if(params==null) return "";
		Map<String, String> map = new HashMap<String, String>();
		for(String param : params){
			String value = request.getParameter(param);
			if(StringUtils.isNotBlank(value)) map.put(param, value);
		}
		JSONObject json = JSONObject.fromObject(map);
		return json.toString();
	}
	public static Map getMapByJson(String json){
		Map result = new HashMap();
		if(StringUtils.isBlank(json)) return result;
		JSONObject ms = JSONObject.fromObject(json);
		result = (Map)ms;
		return result;
	}
	public static String getExceptionTrace(Exception e) {
		StackTraceElement[] traces = e.getStackTrace();
		String result = e.getClass().getCanonicalName() + ": " + e.getMessage();
		for(StackTraceElement trace:traces){
			result += "\n\tat " + trace;
			String[] test = result.split("\n");
			result = StringUtils.join(test, "\n");
		}
		return result;
	}
}
